import React, { useEffect, useMemo, useState } from "react";
import './WrjStanding.less'
import {Button,Table, Dropdown,Modal } from 'antd';
import type { MenuProps} from 'antd';
import request from "../../../utils/axios";
import {EllipsisOutlined,ExclamationCircleOutlined} from '@ant-design/icons';
import { useNavigate } from "react-router-dom";
import moment from 'moment';
import { useSelector } from "react-redux";


const Standing: React.FC =()=>{

    const navigate=useNavigate()

    const [standingList,setStandingList]=useState<DataType[]>([])
    interface DataType {
        key:React.Key,
        _id:string;
        name: string;
        description: string;
        newTime: string;
    }

    const getStanding=async()=>{
        request.get('getstanding').then(error=>{
            console.log(error);
        }).catch(response=>{
            setStandingList(response.data.standingList)
        })
    }

    const columns: any= [
        { title: '编号', dataIndex: 'index' ,key:'index'},
        { title: '身份名称', dataIndex: 'name' ,key:'name'},
        { title: '身份描述', dataIndex: 'description' ,key:'description'},
        { 
            title: '创建时间', 
            dataIndex: 'newTime' ,key:'newTime',
            sorter: (a: DataType, b: DataType) => moment(a.newTime, 'YYYY-MM-DD HH:mm:ss').unix() - moment(b.newTime, 'YYYY-MM-DD HH:mm:ss').unix(),
            sortDirections: ['descend', 'ascend'],
        },
        { title: '操作', dataIndex: 'caozuo' ,key:'caozuo'}
    ];

    const newlist=useMemo(()=>{
        let list:any=[]
        standingList.forEach(item=>{
            if(item.name!='超级管理员'){
                list.push(item)
            }
        })
        return list
    },[standingList])

    const items = [
        {
          key: '1',
          label: '查看身份信息'
        },
        {
          key: '2',
          label: '修改身份信息'
        },
        {
          key: '3',
          label: '删除身份信息'
        },
    ];

    const items2 = [
        {
          key: '1',
          label: '查看身份信息'
        }
    ];

    const standingName=useSelector((store:any)=>store.counter.standingName)
    const dataSource:any = standingList.map((item:DataType,index:number) => {
        return {
            index:index+1,
            name:item.name,
            description:item.description,
            newTime:item.newTime.split('T')[0]+' '+item.newTime.split('T')[1].split('.')[0],
            caozuo:standingName=='超级管理员' || standingName=='管理员'?
            [
                <Dropdown menu={{items,onClick: (e) => {
                    if(e.key=='1'){
                        navigate(`/app/standingadd?editId=${item._id}&title=查看身份`)
                    }else if(e.key=='2'){
                        navigate(`/app/standingadd?editId=${item._id}&title=编辑身份`)
                    }else if(e.key=='3'){
                        Modal.confirm({
                            title: `确定要删除${item.name}吗？`,
                            icon: <ExclamationCircleOutlined />,
                            content: '身份被删除后将无法恢复，请谨慎操作',
                            okText: '确定',
                            cancelText: '取消',
                            onOk: async() => {
                                try {
                                    await request.deleteParam(`delstanding/${item._id}`);
                                } catch (error) {
                                    console.error('DELETE (param) error:', error);
                                }
                            },
                        });
                    }
                }}} trigger={['click']} placement="bottom">
                    <EllipsisOutlined />
                </Dropdown>
            ]:
            [
                <Dropdown menu={{items:items2,onClick: (e) => {
                    if(e.key=='1'){
                        navigate(`/app/standingadd?editId=${item._id}&title=查看身份`)
                    }
                }}} trigger={['click']} placement="bottom">
                    <EllipsisOutlined />
                </Dropdown>
            ]
        }
    });


    useEffect(()=>{getStanding()},[])

    return (
        <div className="wrj-standing-box">
            <div>
                {
                    standingName=='超级管理员' || standingName=='管理员'?
                    <Button onClick={()=>{navigate('/app/standingadd?id=""&title='+'添加身份')}} type='primary' shape="round" size='middle' style={{color:'#fff',marginRight:'20px'}} className="wrj-standing-search-button">+添加身份({standingList.length}/10)</Button>:
                    <></>
                }
                <Table columns={columns} dataSource={dataSource} rowKey={(record) => record._id}/>
            </div>
        </div>
    )
}

export default Standing